package com.huawei.zyb.taskManager.infrastructure.persistence.repository;

import com.huawei.zyb.taskManager.domain.task.entity.Task;
import com.huawei.zyb.taskManager.domain.task.repository.TaskRepository;
import com.huawei.zyb.taskManager.domain.task.valueobject.*;
import com.huawei.zyb.taskManager.domain.developer.valueobject.DeveloperId;
import com.huawei.zyb.taskManager.domain.requirement.valueobject.RequirementId;
import com.huawei.zyb.taskManager.infrastructure.persistence.mapper.TaskMapper;
import com.huawei.zyb.taskManager.infrastructure.persistence.po.TaskPO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 任务仓储实现
 */
@Repository
public class TaskRepositoryImpl implements TaskRepository {
    
    @Autowired
    private TaskMapper taskMapper;
    
    @Override
    public Task save(Task task) {
        System.out.println("[DEBUG] TaskRepository.save() 开始保存任务");
        TaskPO taskPO = toTaskPO(task);
        System.out.println("[DEBUG] 转换为TaskPO完成，ID: " + taskPO.getId());
        System.out.println("[DEBUG] TaskPO详情: title=" + taskPO.getTitle() + ", level=" + taskPO.getLevel() + ", requirementId=" + taskPO.getRequirementId());
        
        // 检查数据库中是否已存在该ID的记录
        boolean exists = taskPO.getId() != null && existsById(TaskId.of(taskPO.getId()));
        System.out.println("[DEBUG] 数据库中是否存在ID " + taskPO.getId() + " 的记录: " + exists);
        
        if (!exists) {
            System.out.println("[DEBUG] 执行insert操作");
            int result = taskMapper.insert(taskPO);
            System.out.println("[DEBUG] insert操作结果: " + result + ", 生成的ID: " + taskPO.getId());
            // 将数据库生成的ID设置回Task对象
            if (taskPO.getId() != null && task.getId() == null) {
                // 这里需要通过反射或其他方式设置Task的ID，但由于Task是不可变的，
                // 我们返回时会重新查询，所以这里暂时不处理
                System.out.println("[DEBUG] 数据库生成的新ID: " + taskPO.getId());
            }
        } else {
            System.out.println("[DEBUG] 执行update操作");
            int result = taskMapper.update(taskPO);
            System.out.println("[DEBUG] update操作结果: " + result);
        }
        
        System.out.println("[DEBUG] TaskRepository.save() 完成");
        
        // 如果是新插入的记录，需要根据生成的ID重新查询返回完整对象
        if (!exists && taskPO.getId() != null) {
            System.out.println("[DEBUG] 重新查询新插入的任务，ID: " + taskPO.getId());
            return findById(TaskId.of(taskPO.getId())).orElse(task);
        }
        
        return task;
    }
    
    @Override
    public Optional<Task> findById(TaskId taskId) {
        TaskPO taskPO = taskMapper.findById(taskId.getValue());
        return taskPO != null ? Optional.of(toTask(taskPO)) : Optional.empty();
    }
    
    @Override
    public List<Task> findByRequirementId(Long requirementId) {
        List<TaskPO> taskPOs = taskMapper.findByRequirementId(requirementId);
        return taskPOs.stream().map(this::toTask).collect(Collectors.toList());
    }
    
    @Override
    public List<Task> findByAssigneeId(String assigneeId) {
        List<TaskPO> taskPOs = taskMapper.findByAssigneeId(assigneeId);
        return taskPOs.stream().map(this::toTask).collect(Collectors.toList());
    }
    
    @Override
    public List<Task> findByParentTaskId(TaskId parentTaskId) {
        List<TaskPO> taskPOs = taskMapper.findByParentTaskId(parentTaskId.getValue());
        return taskPOs.stream().map(this::toTask).collect(Collectors.toList());
    }
    
    @Override
    public List<Task> findByStatus(TaskStatus status) {
        List<TaskPO> taskPOs = taskMapper.findByStatus(status.name());
        return taskPOs.stream().map(this::toTask).collect(Collectors.toList());
    }
    
    @Override
    public List<Task> findByLevel(TaskLevel level) {
        List<TaskPO> taskPOs = taskMapper.findByLevel(level.name());
        return taskPOs.stream().map(this::toTask).collect(Collectors.toList());
    }
    
    @Override
    public List<Task> findAll() {
        List<TaskPO> taskPOs = taskMapper.findAll();
        return taskPOs.stream().map(this::toTask).collect(Collectors.toList());
    }
    
    @Override
    public void deleteById(TaskId taskId) {
        taskMapper.deleteById(taskId.getValue());
    }
    
    @Override
    public boolean existsById(TaskId taskId) {
        return taskMapper.existsById(taskId.getValue());
    }
    
    @Override
    public boolean hasIncompleteSubTasks(TaskId parentTaskId) {
        return taskMapper.hasIncompleteSubTasks(parentTaskId.getValue());
    }
    
    @Override
    public List<Task> findAllSubTasksRecursively(TaskId parentTaskId) {
        List<TaskPO> taskPOs = taskMapper.findAllSubTasksRecursively(parentTaskId.getValue());
        return taskPOs.stream().map(this::toTask).collect(Collectors.toList());
    }
    
    @Override
    public long count() {
        return taskMapper.count();
    }
    
    @Override
    public long countByStatus(TaskStatus status) {
        return taskMapper.countByStatus(status.name());
    }
    
    @Override
    public long countByPriority(TaskPriority priority) {
        return taskMapper.countByPriority(priority.name());
    }
    
    /**
     * 将领域对象转换为持久化对象
     */
    private TaskPO toTaskPO(Task task) {
        TaskPO taskPO = new TaskPO();
        if (task.getId() != null) {
            taskPO.setId(task.getId().getValue());
        }
        // 如果task.getId()为null，taskPO.getId()也保持为null，让数据库自动生成
        taskPO.setTitle(task.getTitle().getValue());
        taskPO.setDescription(task.getDescription() != null ? task.getDescription().getValue() : null);
        taskPO.setStatus(task.getStatus().name());
        taskPO.setProgress(task.getProgress().getValue());
        taskPO.setPriority(task.getPriority().name());
        taskPO.setLevel(task.getLevel().name());
        taskPO.setAssigneeId(task.getAssigneeId());
        taskPO.setRequirementId(task.getRequirementId());
        taskPO.setParentTaskId(task.getParentTaskId() != null ? task.getParentTaskId().getValue() : null);
        taskPO.setEstimatedHours(task.getEstimatedHours() != null ? task.getEstimatedHours().getValue() : null);
        taskPO.setActualHours(task.getActualHours() != null ? task.getActualHours().getValue() : null);
        taskPO.setCreatedAt(task.getCreatedAt());
        taskPO.setUpdatedAt(task.getUpdatedAt());
        return taskPO;
    }
    
    /**
     * 将持久化对象转换为领域对象
     */
    private Task toTask(TaskPO taskPO) {
        return Task.restore(
            TaskId.of(taskPO.getId()),
            TaskTitle.of(taskPO.getTitle()),
            taskPO.getDescription() != null ? TaskDescription.of(taskPO.getDescription()) : null,
            TaskStatus.valueOf(taskPO.getStatus()),
            TaskProgress.of(taskPO.getProgress()),
            TaskPriority.valueOf(taskPO.getPriority()),
            TaskLevel.valueOf(taskPO.getLevel()),
            taskPO.getAssigneeId(),
            taskPO.getRequirementId(),
            taskPO.getParentTaskId() != null ? TaskId.of(taskPO.getParentTaskId()) : null,
            taskPO.getEstimatedHours() != null ? EstimatedHours.of(taskPO.getEstimatedHours()) : null,
            taskPO.getActualHours() != null ? ActualHours.of(taskPO.getActualHours()) : null,
            taskPO.getCreatedAt(),
            taskPO.getUpdatedAt()
        );
    }
}